<template>
    <view class="container">
        <!-- 返回首页按钮 -->
        <view class="back-section">
            <button @click="goToHome" class="back-btn">
                <text class="icon">←</text> 返回首页
            </button>
        </view>

        <!-- 各类别游客评价分数 -->
        <view class="chart-section">
            <text class="chart-title">各类别游客评价分数</text>
            <view class="chart-container">
                <view v-for="(item, index) in reviewScoresData" :key="index" class="bar-item">
                    <view class="bar-label">{{ item.category }}</view>
                    <view class="bar-wrapper">
                        <view 
                            class="bar-fill" 
                            :style="{ 
                                width: (item.score / 5) * 100 + '%',
                                backgroundColor: colors[index % colors.length]
                            }"
                        ></view>
                    </view>
                    <text class="bar-value">{{ item.score }}</text>
                </view>
            </view>
        </view>

        <!-- 各类别旺季客流量峰值 -->
        <view class="chart-section">
            <text class="chart-title">各类别旺季客流量峰值</text>
            <view class="chart-container">
                <view v-for="(item, index) in peakTrafficData" :key="index" class="bar-item">
                    <view class="bar-label">{{ item.category }}</view>
                    <view class="bar-wrapper">
                        <view 
                            class="bar-fill" 
                            :style="{ 
                                width: (item.peakValue / Math.max(...peakTrafficData.map(i => i.peakValue))) * 100 + '%',
                                backgroundColor: colors[index % colors.length]
                            }"
                        ></view>
                    </view>
                    <text class="bar-value">{{ item.peakValue }}</text>
                </view>
            </view>
        </view>

        <!-- 热门打卡点排行 - 竖向柱状图 -->
        <view class="chart-section">
            <text class="chart-title">热门打卡点排行</text>
            <view class="vertical-chart-container">
                <!-- Y轴标签 -->
                <view class="y-axis">
                    <view v-for="tick in yAxisTicks" :key="tick" class="y-tick">
                        <text class="y-label">{{ formatNumber(tick) }}</text>
                    </view>
                </view>
                
                <!-- 图表主体 -->
                <view class="chart-main">
                    <!-- 网格线 -->
                    <view class="grid-lines">
                        <view v-for="tick in yAxisTicks" :key="tick" class="grid-line"></view>
                    </view>
                    
                    <!-- 柱状图 -->
                    <view class="bars-container">
                        <view 
                            v-for="(item, index) in checkinTopData" 
                            :key="index" 
                            class="vertical-bar-item"
                        >
                            <view class="bar-column">
                                <view 
                                    class="vertical-bar-fill" 
                                    :style="{ 
                                        height: (item.checkinCount / maxCheckinCount) * 100 + '%',
                                        backgroundColor: colors[index % colors.length]
                                    }"
                                >
                                    <text class="bar-top-value">{{ formatNumber(item.checkinCount) }}</text>
                                </view>
                            </view>
                            <text class="x-label">{{ item.spotName }}</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 刷新按钮 -->
        <view class="refresh-section">
            <button @click="refreshData" class="refresh-btn" :disabled="loading">
                {{ loading ? '加载中...' : '刷新数据' }}
            </button>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const token = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0VXNlcjEiLCJleHAiOjE3NTA5MTU5NDQsImlhdCI6MTc1MDgyOTU0NH0.yQboYi9I4doev_bAJzOSikxGOl1S2rubHdUAYZWlorc40pFTFEwctBurw_p0UKHEVUF4LQZamavFtCIZ39k2Yg'

const colors = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC']
const loading = ref(false)

// 模拟数据
const mockReviewScores = [
    { category: '自然风光', score: 4.5 },
    { category: '历史文化', score: 4.2 },
    { category: '美食体验', score: 4.7 },
    { category: '住宿服务', score: 4.1 },
    { category: '交通便利', score: 3.8 }
]

const mockPeakTraffic = [
    { category: '自然风光', peakValue: 15000 },
    { category: '历史文化', peakValue: 12000 },
    { category: '美食体验', peakValue: 18000 },
    { category: '住宿服务', peakValue: 8000 },
    { category: '交通便利', peakValue: 10000 }
]

const mockCheckinTop = [
    { spotName: '天安门广场', checkinCount: 25000 },
    { spotName: '故宫博物院', checkinCount: 22000 },
    { spotName: '长城', checkinCount: 20000 },
    { spotName: '颐和园', checkinCount: 15000 },
    { spotName: '天坛公园', checkinCount: 12000 }
]

// 数据
const reviewScoresData = ref([])
const peakTrafficData = ref([])
const checkinTopData = ref([])

// 计算属性
const maxCheckinCount = computed(() => {
    if (checkinTopData.value.length === 0) return 30000
    return Math.max(...checkinTopData.value.map(item => item.checkinCount))
})

const yAxisTicks = computed(() => {
    const max = maxCheckinCount.value
    const step = Math.ceil(max / 5 / 1000) * 1000 // 向上取整到千位
    return Array.from({ length: 6 }, (_, i) => step * i).reverse()
})

// 格式化数字显示
const formatNumber = (num) => {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k'
    }
    return num.toString()
}

// 返回首页

const goToHome = () => {
  uni.navigateTo({ url: '/pages/home/home' })
}

// 获取数据的函数
const fetchReviewScores = async () => {
    try {
        // 尝试从真实接口获取数据
        const response = await uni.request({
            url: 'http://localhost:8080/api/statistics/review-scores',
            method: 'GET',
            header: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            timeout: 5000
        })
        
        if (response.statusCode === 200) {
            reviewScoresData.value = response.data
        } else {
            throw new Error('接口返回错误')
        }
    } catch (error) {
        console.log('评价分数')
        reviewScoresData.value = mockReviewScores
    }
}

const fetchPeakTraffic = async () => {
    try {
        const response = await uni.request({
            url: 'http://localhost:8080/api/statistics/peak-traffic',
            method: 'GET',
            header: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            timeout: 5000
        })
        
        if (response.statusCode === 200) {
            peakTrafficData.value = response.data
        } else {
            throw new Error('接口返回错误')
        }
    } catch (error) {
        console.log('客流量峰值')
        peakTrafficData.value = mockPeakTraffic
    }
}

const fetchCheckinTop = async () => {
    try {
        const response = await uni.request({
            url: 'http://localhost:8080/api/statistics/checkin-top',
            method: 'GET',
            header: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            timeout: 5000
        })
        
        if (response.statusCode === 200) {
            checkinTopData.value = response.data
        } else {
            throw new Error('接口返回错误')
        }
    } catch (error) {
        console.log('打卡排行')
        checkinTopData.value = mockCheckinTop
    }
}

const refreshData = async () => {
    loading.value = true
    try {
        await Promise.all([
            fetchReviewScores(),
            fetchPeakTraffic(),
            fetchCheckinTop()
        ])
        uni.showToast({
            title: '数据刷新成功',
            icon: 'success'
        })
    } catch (error) {
        uni.showToast({
            title: '刷新失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    refreshData()
})
</script>

<style scoped>
.container {
    padding: 20rpx;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 返回按钮样式 */
.back-section {
    padding: 20rpx 0;
    margin-bottom: 20rpx;
}

.back-btn {
    background-color: #f8f8f8;
    color: #0000ff;
    border: 1rpx solid #ddd;
    border-radius: 50rpx;
    padding: 15rpx 30rpx;
    font-size: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.back-btn .icon {
    margin-right: 10rpx;
    font-weight: bold;
}

.chart-section {
    background-color: #ffffff;
    margin-bottom: 30rpx;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.chart-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 30rpx;
    display: block;
    text-align: center;
}

.chart-container {
    width: 100%;
}

.bar-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    padding: 10rpx 0;
}

.bar-label {
    width: 160rpx;
    font-size: 28rpx;
    color: #666666;
    text-align: right;
    margin-right: 20rpx;
    flex-shrink: 0;
}

.bar-wrapper {
    flex: 1;
    height: 40rpx;
    background-color: #f0f0f0;
    border-radius: 20rpx;
    overflow: hidden;
    margin-right: 20rpx;
}

.bar-fill {
    height: 100%;
    border-radius: 20rpx;
    transition: width 0.3s ease;
    min-width: 20rpx;
}

.bar-value {
    width: 100rpx;
    font-size: 28rpx;
    font-weight: bold;
    color: #333333;
    text-align: center;
    flex-shrink: 0;
}

/* 竖向柱状图样式 */
.vertical-chart-container {
    display: flex;
    height: 500rpx;
    margin-top: 20rpx;
}

.y-axis {
    width: 80rpx;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-right: 20rpx;
    padding-top: 40rpx;
    padding-bottom: 40rpx;
}

.y-tick {
    position: relative;
    height: 0;
}

.y-label {
    font-size: 24rpx;
    color: #666666;
    position: absolute;
    right: 10rpx;
    transform: translateY(-50%);
}

.chart-main {
    flex: 1;
    position: relative;
    height: 100%;
}

.grid-lines {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding-top: 40rpx;
    padding-bottom: 40rpx;
}

.grid-line {
    height: 1rpx;
    background-color: #e0e0e0;
    width: 100%;
}

.bars-container {
    position: absolute;
    top: 40rpx;
    bottom: 40rpx;
    left: 0;
    right: 0;
    display: flex;
    align-items: flex-end;
    justify-content: space-around;
    padding: 0 20rpx;
}

.vertical-bar-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100%;
    flex: 1;
    max-width: 120rpx;
}

.bar-column {
    height: 100%;
    width: 60rpx;
    display: flex;
    align-items: flex-end;
    margin-bottom: 10rpx;
}

.vertical-bar-fill {
    width: 100%;
    border-radius: 8rpx 8rpx 0 0;
    transition: height 0.5s ease;
    position: relative;
    min-height: 20rpx;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding-top: 10rpx;
}

.bar-top-value {
    font-size: 20rpx;
    color: white;
    font-weight: bold;
    text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
}

.x-label {
    font-size: 24rpx;
    color: #666666;
    text-align: center;
    line-height: 1.2;
    word-break: break-all;
    max-width: 100rpx;
}

.refresh-section {
    padding: 40rpx 0;
    text-align: center;
}

.refresh-btn {
    background-color: #007aff;
    color: white;
    border: none;
    border-radius: 50rpx;
    padding: 20rpx 60rpx;
    font-size: 32rpx;
}

.refresh-btn[disabled] {
    background-color: #cccccc;
}
</style>